package config

import (
	"fmt"
	"log"

	"github.com/BurntSushi/toml"
)

type Config struct {
	Database DatabaseConf `json:"database" toml:"database"`
	Server   ServerConf   `json:"server" toml:"server"`
	Logger   LoggerConf   `json:"logger" toml:"logger"`
	Auth     AuthConf     `json:"auth" toml:"auth"`
}

type DatabaseConf struct {
	Username    string `json:"username" toml:"username"`
	Password    string `json:"pasword" toml:"password"`
	Host        string `json:"host" toml:"host"`
	Port        int    `json:"port" toml:"port"`
	ServiceName string `json:"service_name" toml:"service_name"`
}

func (dc *DatabaseConf) GetDsn() string {
	return fmt.Sprintf("%s/%s@//%s:%d/%s",
		dc.Username, dc.Password, dc.Host, dc.Port, dc.ServiceName)
}

type ServerConf struct {
	Port     int `json:"port" toml:"port"`
	Interval int `json:"interval" toml:"interval"`
}

func (s ServerConf) GetPort() string {
	return fmt.Sprintf(":%d", s.Port)
}

type LoggerConf struct {
	Enable bool   `json:"enable" toml:"enable"`
	Path   string `json:"path" toml:"path"`
}

type AuthConf struct {
	Enable   bool   `json:"enable" toml:"enable"`
	Username string `json:"username" toml:"username"`
	Password string `json:"password" toml:"password"`
}

var C = &Config{}

func LoadConfigToml(file string) {
	_, err := toml.DecodeFile(file, &C)
	if err != nil {
		log.Fatalf("Failed to parse TOML config: %v", err.Error())
	}
	log.Println("Load Config:", file)
}
